#include "QtSceneGraphics.h"
#include "SceneItem.h"
#include "GameWidget.h"
#include "Field.h"

#include <QtGui>
#include <iostream>
#include <sstream>

using namespace std;

void QtSceneGraphics::paint( int x, int y, Object* o ){
    QGraphicsItem* item;

    if( o ) item = new SceneItem( o );
    else item = 0;

    if( scene->itemAt( SceneItem::RECTWIDTH * x, SceneItem::RECTHEIGHT * y )
        && scene->itemAt( SceneItem::RECTWIDTH * x, SceneItem::RECTHEIGHT * y ) != item ){
        QGraphicsItem* oldItem = scene->itemAt( SceneItem::RECTWIDTH * x,
                                                SceneItem::RECTHEIGHT * y );
        scene->removeItem( oldItem );
        delete oldItem;
    }
    if( !o ) return;

    item->setPos( SceneItem::RECTWIDTH * x, SceneItem::RECTHEIGHT * y );
    scene->addItem( item );
    //if( !widget->isActiveWindow() ) widget->activateWindow();
}

void QtSceneGraphics::paintAll() {
    QGraphicsView* view = getView();
    QLayout* layout = widget->layout();
    QLabel* score = widget->getScore();
    QLabel* stats = widget->getStats();
    string str;
    QString displayed;
    Field* field = widget->getField();
    Mob* player = field->getPlayer();
    stringstream stream, stream2;
    static bool added = 0;
    if( !added){
        layout->addWidget( view );
        widget->setLayout( layout );
        added = 1;
    }
    if( player != 0 )  stream << "Lifes: " << player->getLifes() << " Speed: "
                              << player->getMoveSpeed() << " Shifts: " << player->getShifts() << " ";
    else stream << "Lifes: DEAD Speed: Dead don't move Shifts: How do you imagine this?";
    str = stream.str();
    displayed = str.c_str();
    stats->setText( displayed );
    displayed.clear();
    str.clear();

    stream2 << "SCORE " << field->getDeathsOfRed() << " " << field->getDeathsOfGreen();
    str = stream2.str();
    displayed = str.c_str();
    score->setText( displayed );
    view->setScene( scene );
    widget->show();
}

void QtSceneGraphics::deleteResourses( int x, int y ){
    QGraphicsScene* scene = getScene();
    if( scene->itemAt( SceneItem::RECTWIDTH * x, SceneItem::RECTHEIGHT * y ) ){
        delete scene->itemAt( SceneItem::RECTWIDTH * x, SceneItem::RECTHEIGHT * y );
    }
}
